//
//  ShowHomeMainViewController.m
//  wAudioShare
//
//  Created by Anson on 14-3-30.
//  Copyright (c) 2014年 赵帅. All rights reserved.
//

#import "ShowHomeMainViewController.h"

#import <netinet/in.h>
#import <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#import "pthread.h"

#import "WISInterfaces.h"
#import "wis.h"
#import <netdb.h>

#import "DemoUpnpViewController.h"
#import "RemoteControlViewController.h"
#import "DeviceListViewController.h"
#import "GlobalVar.h"
#import "WiimuUpnp.h"

#import "DDFileLogger.h"
#import "Utitlity.h"
#import "MMProgressHUD.h"
#import "PersistableInfo.h"
#import "SceneViewController.h"
#import "ArmListViewController.h"
#import "RoomListViewController.h"

#import "AutomationViewController.h"
#import "CameraListViewController.h"
#import "MeterListViewController.h"
#import "RemoteViewController.h"
#import "SensorListViewController.h"

static const int ddLogLevel = LOG_LEVEL_VERBOSE;

#define BUFSIZE 4096
//#define DEVICE_STATUS_UPDATE_TIMER_INTERVAL 300

@interface ShowHomeMainViewController () <serviceGetWISAddressDelegate, MBProgressHUDDelegate, WiimuUpnpDelegate, serviceGetUpdateStatusDelegate,UIActionSheetDelegate,UIAlertViewDelegate>
{
    NSMutableArray *serverArray;
    
    unsigned long m_IP;
    int m_Port;
    BOOL m_bRunning;//控制recv线程循环运行信号
    
    NSThread * m_recvThread;
    NSTimer * remoteDeviceTimer;
    NSTimer *_deviceStatusUpdateTimer;
    
    BOOL m_bRecreateThread;
    
    NSMutableArray *_deviceArr;
    
    MBProgressHUD *_ProgressHUD;
    NSString *ipUrl;
    NSTimer *timer;
    NetworkStatus netStatus;
    int sock;
}

//@property (retain) DemoUpnpViewController * upnpController;
@property (weak, nonatomic) IBOutlet UIButton *setBtn;

@end

@implementation ShowHomeMainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)]) {
        UIImage *image = [UIImage imageNamed: @"bg_top"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
        
        //[self.navigationController.navigationBar setBackgroundColor:[UIColor blueColor]];
        
    }else{
        UIImage *image = [UIImage imageNamed: @"bg_top"];
        CALayer *nbLayer =  self.navigationController.navigationBar.layer;
        nbLayer.contents = (id)image.CGImage;
    }
    
    //self.navigationController.navigationBarHidden = YES;
    
    // Do any additional setup after loading the view from its nib.
    //CGSize size = [UIScreen mainScreen].bounds.size;
    CGRect r = self.mainFuncCircleView.frame;
    r.origin.y = 0;
    //self.mainFuncCircleView.frame = r;
    self.title = @"server mac address";
    
    _deviceArr = [[NSMutableArray alloc] init];
    
    [GlobalInfo sharedInstance].upnpArray = _deviceArr;
    
    serverArray = [[NSMutableArray alloc] initWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:@"Nietech WIS Server",@"name",@"http://www.evalogik.com:5678/wis/webuser/server.php",@"url", nil], nil];
    
    m_bRunning = YES;
    m_bRecreateThread = NO;
    
    //mod by anson 14-03
    //_nameLabel.text = [[GlobalInfo sharedInstance] getUniqueID];
    
    if (![GlobalVar getDataForKey:@"config.domain"]) {
        [GlobalVar saveData:@"localhost" forKey:@"config.domain"];
        [GlobalVar saveData:@"1234" forKey:@"config.port"];
        [GlobalVar saveData:@"test" forKey:@"config.username"];
        [GlobalVar saveData:@"test" forKey:@"config.password"];
    }
    
    [self.setBtn addTarget:self action:@selector(setedActSheet) forControlEvents:UIControlEventTouchUpInside];
    self.setBtn.hidden = YES;
    
    [self inituPnPDetect];
    
    timer=[NSTimer scheduledTimerWithTimeInterval:3
                                           target:self
                                         selector:@selector(checkIPChanged)
                                         userInfo:nil
                                          repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    //self.navigationController.navigationBarHidden = YES;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *titleStr = [user objectForKey:@"device"];
    
    [GlobalService sharedInstance].curOperationDeviceUUID  = titleStr;
    
    [self updateNavTitle:[GlobalService sharedInstance].curOperationDeviceUUID];
    
    if (!m_recvThread.isExecuting) {
        [self performSelector:@selector(connectNieTechWISServer) withObject:nil];
    }

}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    [[WiimuUpnp sharedInstance] stopSSDP];
}

//检查ip变化
- (void)checkIPChanged
{
    netStatus = [[WiimuUpnp sharedInstance].wifiReach currentReachabilityStatus];
    if(netStatus == ReachableViaWiFi)
    {
        if ([[GlobalService sharedInstance] checkIfIPChanged])
        {
            dispatch_async(dispatch_get_global_queue(0, 0), ^{
                [self connectNieTechWISServer];
            });
        }
    }
}

- (void)setedActSheet
{
    UIActionSheet *setList = [[UIActionSheet alloc] initWithTitle:@"设置" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"resetDevice",@"增加设备",@"删除设备",nil];
    [setList showInView:self.view];
}

-(BOOL)isNavigationBackEnabled
{
    return NO;
}

#pragma mark - Connect Server
-(void)popToRootWithError
{
    //if(![self.navigationController.topViewController isKindOfClass:[ShowHomeMainViewController class]])
    {
        [self.view makeToast:@"连接失败"
                    duration:3.0
                    position:@"bottom"
                       title:@"提示"];
        
    }
}

#pragma mark - Button
- (BOOL)isRemoteDeviceConnected {
    
    if ([GlobalService sharedInstance].curOperationDeviceUUID.length == 0) {
    
        [self.view makeToast:NSLocalizedString(@"ALERT_NO_GATEWAY", @"")  duration:1.0 position:@"center"];
        return FALSE;
    }
    return TRUE;
}

//灯泡
-(IBAction)gotoDeviceAutomation:(id)sender
{
    if ([self isRemoteDeviceConnected]) {
    
        AutomationViewController *autom = [[AutomationViewController alloc] init];
        autom.title = @"Automation";
        [self.navigationController pushViewController:autom animated:YES];
        
//    DeviceListViewController *dlvc = [[DeviceListViewController alloc] init];
//    dlvc.type = DeviceAutomation;
//    [self.navigationController pushViewController:dlvc animated:YES];
        
    }
}

//设置
-(IBAction)gotoSetting:(id)sender
{
    [self enterUPNPController];
}

//摄像头
-(IBAction)gotoDeviceCamera:(id)sender
{
    if ([self isRemoteDeviceConnected]) {

        CameraListViewController *camer = [[CameraListViewController alloc] init];
        [self.navigationController pushViewController:camer animated:YES];
        
//    DeviceListViewController *dlvc = [[DeviceListViewController alloc] init];
//    dlvc.type = DeviceCamera;
//    [self.navigationController pushViewController:dlvc animated:YES];
    }
}

//遥控
-(IBAction)gotoDeviceRemote:(id)sender
{
    if ([self isRemoteDeviceConnected]) {

        RemoteViewController *camer = [[RemoteViewController alloc] init];
        [self.navigationController pushViewController:camer animated:YES];
        
//    DeviceListViewController *dlvc = [[DeviceListViewController alloc] init];
//    dlvc.type = DeviceRemote;
//    [self.navigationController pushViewController:dlvc animated:YES];
    }
}

//Meter
-(IBAction)gotoDeviceMeter:(id)sender
{
    if ([self isRemoteDeviceConnected]) {
        
        MeterListViewController *camer = [[MeterListViewController alloc] init];
        camer.title = @"Meter";
        [self.navigationController pushViewController:camer animated:YES];
        
//    DeviceListViewController *dlvc = [[DeviceListViewController alloc] init];
//    dlvc.type = DeviceMeter;
//    [self.navigationController pushViewController:dlvc animated:YES];
    }
}

//Scenes
- (IBAction)gotoScenes:(id)sender {
 
    if ([self isRemoteDeviceConnected]) {
    SceneViewController *vc = [[SceneViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    }
}

//!进入条件Association View
- (IBAction)gotoAssociation:(id)sender {

    if ([self isRemoteDeviceConnected]) {

    ArmListViewController *vc = [[ArmListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
    }
}

//!房间
- (IBAction)gotoRoomList:(id)sender {
    
    if ([self isRemoteDeviceConnected]) {

        RoomListViewController *vc = [[RoomListViewController alloc] initWithNibName:nil bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)gotoSensor:(id)sender {
    
    SensorListViewController *vc = [[SensorListViewController alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)btnAutomationDeviceAddOrDel:(id)sender {
    
    UIActionSheet *menu = [[UIActionSheet alloc]
                           initWithTitle: nil
                           delegate:self
                           cancelButtonTitle:@"取消"
                           destructiveButtonTitle:nil
                           otherButtonTitles:@"添加设备",@"删除设备", nil];
    menu.tag = 200;
    [menu showInView:self.view];
}

#pragma mark - Setting
- (void)connectNieTechWISServer
{
    dispatch_async(dispatch_get_main_queue(), ^{
        if(![_ProgressHUD isDescendantOfView:self.navigationController.view])
        {
            _ProgressHUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
            [self.navigationController.view addSubview:_ProgressHUD];
            _ProgressHUD.removeFromSuperViewOnHide = YES;
            _ProgressHUD.delegate = self;
            _ProgressHUD.labelText = @"Server Connecting...";
            
            //!登录可以放到后台去， 登录只会影响在外网的控制，不登录的情况下，内网http请求也是可以控制的。
            //[_ProgressHUD show:YES];
        }
    });
    
    
    if([GlobalInfo sharedInstance].m_CmdSock != 0)
    {
        m_bRunning = NO;
    }
    
    double delayInSeconds = 1;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        [[GlobalService sharedInstance] getWISAddress:self url:[[serverArray lastObject] objectForKey:@"url"]];
    });
}

-(void)serviceGetWISAddressCallBack:(NSDictionary*)dicCallBack
{
    if(![[dicCallBack objectForKey:@"responsestatus"] isEqualToString:SERVICE_SUCCESS])
    {
        [self logText:@"获取server信息失败"];
        //[MMProgressHUD dismiss];
        dispatch_async(dispatch_get_main_queue(), ^{
            [_ProgressHUD hide:YES];
        });
        
        return;
    }
    
    [self logText:@"获取server信息成功"];
    m_Port = [[dicCallBack objectForKey:@"port"] intValue];
    
    NSString* tempIP = [self getTrueIP:[dicCallBack objectForKey:@"host"]];
    
    m_IP = inet_addr([tempIP UTF8String]);
    NSLog(@"ServerIP:%@ m_IP:%lu", tempIP, m_IP);
    
    [self performSelectorInBackground:@selector(attempToCreateThread) withObject:nil];
}

-(void)enterUPNPController
{
    if([self.navigationController.topViewController isKindOfClass:[ShowHomeMainViewController class]])
    {
        DemoUpnpViewController *upnpController = [[DemoUpnpViewController alloc] initWithNibName:@"DemoUpnpViewController" bundle:nil];
        [self.navigationController pushViewController:upnpController animated:YES];
    }
}

#pragma mark - private methods
- (BOOL)isPureInt:(NSString*)string{
    NSScanner* scan = [NSScanner scannerWithString:string];
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

-(NSString *)getTrueIP:(NSString *)host
{
    NSString * lastChar = [host substringFromIndex:[host length]-2];
    if([self isPureInt:lastChar])
    {
        return host;
    }
    else
    {
        NSString * hostStr = nil;
        if([host rangeOfString:@"http://"].location == NSNotFound)
        {
            hostStr = [NSString stringWithFormat:@"http://%@",host];
        }
        else
        {
            hostStr = host;
        }
        
        NSURL * url = [NSURL URLWithString:hostStr];
        char * str = (char *)[[url host] UTF8String];
        struct hostent *remoteHostEnt = gethostbyname(str);
        struct in_addr *remoteInAddr = (struct in_addr *) remoteHostEnt->h_addr_list[0];
        char *sRemoteInAddr = inet_ntoa(*remoteInAddr);
        NSString* hostIP = [NSString stringWithUTF8String:sRemoteInAddr];
        
        return hostIP;
    }
}

#pragma mark - Thread
-(void)getRemoteDeviceTimerMethod
{
    [WISInterfaces wis_send_get_devices_cmd:[GlobalInfo sharedInstance].m_CmdSock];
    
}

-(void)attempToCreateThread
{
    while ([GlobalInfo sharedInstance].m_CmdSock != 0) {
        [NSThread sleepForTimeInterval:0.1];
    }
    
    NSLog(@"create thread");
    
    if(![m_recvThread isCancelled])
    {
        [m_recvThread cancel];
    }
    m_recvThread = nil;
    
    m_bRecreateThread = TRUE;
    m_bRunning = YES;
    m_recvThread = [[NSThread alloc] initWithTarget:self selector:@selector(TCPRun) object:nil];
    [m_recvThread start];
    
}

-(void)TCPRun
{
    [self performSelectorOnMainThread:@selector(logText:) withObject:@"开始连接服务器" waitUntilDone:YES];
    
    int ret;
    sock = 0;
	in_addr in;
	struct sockaddr_in localAddr;
	struct sockaddr_in server;
	struct timeval t;
	int error = 0;
	socklen_t errlen = sizeof(errlen);
	u_long iMode = 1;
	fd_set wrfds;
	fd_set rdfds;
    int reconnectTime = 0;
    
   WisSocketCmd* msg = ( WisSocketCmd *) malloc (MAX_WIS_DATA_LEN
                                                  + sizeof(WisSocketCmd));
	while(m_bRunning)
	{
		int handle = 0;
		int retry_count = 0;
        
		sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
        
		localAddr.sin_family = AF_INET;
		localAddr.sin_addr.s_addr = INADDR_ANY;
		localAddr.sin_port = 0;
		ret = bind(sock, (struct sockaddr*)&localAddr, sizeof(localAddr));
		if (ret == -1)
		{
			printf("AMirrorClient::TcpRun bind  socket failed\r\n");
			goto RECONNECT;
		}
        
		ioctl(sock, FIONBIO, (u_long*)&iMode);
		{
			//int nSendBuf=65535;
			//setsockopt(sock,SOL_SOCKET,SO_RCVBUF,(char*)&nSendBuf,sizeof(int));
			//nSendBuf=65535;
			//setsockopt(sock,SOL_SOCKET,SO_SNDBUF,(char*)&nSendBuf,sizeof(int));
            //setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, , )
            int noSigPipe = 1;
            setsockopt(sock, SOL_SOCKET, SO_NOSIGPIPE, &noSigPipe, sizeof(noSigPipe));
		}
        
		in.s_addr = m_IP;
        
		server.sin_family = AF_INET;
		server.sin_addr.s_addr = m_IP;
        server.sin_port = htons(m_Port);
		ret = connect(sock, (sockaddr*)&server, sizeof(server));
		if (ret == -1)
		{
			if(errno != EINPROGRESS)
			{
				printf("AMirrorClient::TcpRun connect socket return failed\r\n");
				goto RECONNECT;
			}
			
			while(m_bRunning) {
				FD_ZERO(&wrfds);
				FD_SET(sock, &wrfds);
                
				t.tv_sec  =2;
				t.tv_usec =0;
				ret = select(sock+1, 0, &wrfds, 0, &t);
				if(ret < 0) {
					printf("AMirrorClient::TcpRun connect select fail\r\n");
					goto RECONNECT;
				}
                
				if(getsockopt(sock, SOL_SOCKET, SO_ERROR, &error, &errlen) < 0)
				{
					printf("AMirrorClient::TcpRun connect getsockopt fail\n");
					goto RECONNECT;
				}
                
				if(error)
				{
					if(error == ETIMEDOUT)
						printf("AMirrorClient::TcpRun connect timeout\n");
					if(error == ECONNREFUSED)
						printf("AMirrorClient::TcpRun connect refused\n");
					else
						printf("AMirrorClient::TcpRun connect err=%d\n", error);
                    
					goto RECONNECT;
				}
				
				if(ret == 0) {
					if(retry_count++ > 15) {
						printf("AMirrorClient::TcpRun connect retry fail\r\n");
						goto RECONNECT;
					}
                    
					continue;
				}
                
				if(FD_ISSET(sock, &wrfds)) {
					FD_CLR(sock, &wrfds);
					handle = sock;

					printf("AMirrorClient::TcpRun connect ok\r\n");
                    [GlobalInfo sharedInstance].m_CmdSock = handle;
                    
                    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
                    
                    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                        
                        [WISInterfaces wis_send_login_cmd:[GlobalInfo sharedInstance].m_CmdSock name:(char *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String]];
                        
                        
                    });
					break;
				}
			}
		}
		else
		{
			printf("AMirrorClient::TcpRun connect direct ok\r\n");
			handle = sock;
            [GlobalInfo sharedInstance].m_CmdSock = handle;
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC));
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                
                [WISInterfaces wis_send_login_cmd:[GlobalInfo sharedInstance].m_CmdSock name:(char *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String]];
                
            });
		}
        
		if(handle)
		{
            DLog(@"handle:%d",handle);
            [GlobalInfo sharedInstance].m_CmdSock = handle;
            
			while(m_bRunning)
			{
				FD_ZERO(&rdfds);
				FD_SET(handle, &rdfds);
				
				t.tv_sec = 2;
				t.tv_usec = 0;
                
				ret = select(handle+1,&rdfds,0,0,&t);
				if(ret < 0)
				{
					printf("AMirrorClient::TcpRun recv select fail\n");
					goto RECONNECT;
				}
				
				if(ret == 0)
				{
					if(getsockopt(handle, SOL_SOCKET, SO_ERROR, &error, &errlen) < 0)
					{
						printf("AMirrorClient::TcpRun recv select getsockopt fail\n");
						goto RECONNECT;
					}
					
					if(error)
					{
						printf("AMirrorClient::TcpRun recv select  err=%d\n", error);
						goto RECONNECT;
					}
                    
					usleep(10000);
					continue;
				}
                
				if (FD_ISSET(handle, &rdfds))
				{
                    FD_CLR(handle, &rdfds);
					
                    memset((void *)msg, 0, MAX_WIS_DATA_LEN + sizeof(WisSocketCmd));
					ret = recv(handle, msg, sizeof(WisSocketCmd), 0);
					
					if(ret < 0)
					{
						printf("AMirrorClient::TcpRun recv fail\n");
						goto RECONNECT;
					}
                    
					if(ret == 0)
					{
						if(getsockopt(handle, SOL_SOCKET, SO_ERROR, &error, &errlen) < 0)
						{
							printf("AMirrorClient::TcpRun recv getsockopt fail\n");
							goto RECONNECT;
						}
						
						if(error)
						{
							printf("AMirrorClient::TcpRun recv err=%d\n", error);
							goto RECONNECT;
						}
						
						usleep(10000);
						continue;
					}
                    
                    //消息体
                    if ( 0 != msg->cmdDataLength)
                    {
                        int size = msg->cmdDataLength;
                        int count = 0;
                        while(1)
                        {
                            ret = recv(handle,
                                          ((char*)msg+sizeof(WisSocketCmd))+msg->cmdDataLength-size, size, 0);
//                            NSLog(@"handle,received %d %d bytes" ,ret, size);
                            if (ret <= 0)
                            {
                                ++count;
                                if(count <= 1000 )
                                {
                                    usleep(1000);
                                    continue;
                                }
                                NSLog(@"socket 失败");
                            }
                            size -= ret;
                            if( size <= 0 )
                                break;
                            count=0;
                        }
                    }
                    
                    //检测
                    int checksum = 0;
                    for(int i=sizeof(unsigned int); i < sizeof(WisSocketCmd)+msg->cmdDataLength; i++)
                    {
                        checksum += ((unsigned char*)msg)[i];
                    }
                    
                    if (checksum != (msg->checksum)){
                        goto RECONNECT;
                    }
                    
					retry_count = 0;
                    
                    [self dealWithRecvData:msg];
                    
				}
			}
		}
    RECONNECT:
        reconnectTime++;
        if(reconnectTime >= 30)
        {
            dispatch_async(dispatch_get_main_queue(), ^{
                //[MMProgressHUD dismiss];
                [_ProgressHUD hide:YES];
            });
            
            if([self.navigationController.topViewController isKindOfClass:[ShowHomeMainViewController class]])
            {
                [self performSelectorOnMainThread:@selector(logText:) withObject:@"连接服务器失败" waitUntilDone:YES];
            }
            else
            {
                [self performSelectorOnMainThread:@selector(popToRootWithError) withObject:nil waitUntilDone:YES];
            }
            
            m_bRunning = NO;
            
            [GlobalInfo sharedInstance].m_CmdSock=0;
            close(sock);
            sock = 0;
            
            return;
        }
        
        [GlobalInfo sharedInstance].m_CmdSock=0;
        
		close(sock);
		sock = 0;
		usleep(100000);
	}
    
	if(sock)
	{
        [GlobalInfo sharedInstance].m_CmdSock=0;
        
		close(sock);
	}
    
    free(msg);
}


-(void)dealWithRecvData:(WisSocketCmd *)cmd
{
//    int cCmdId;
//    memcpy(&cCmdId, &cmd->cmdId, sizeof(cmd->cmdId));
    //DLog(@"cmdId:%d",cmd->cmdId);
    
    switch(cmd->cmdId)
    {
            /* login  */
        case WIS_CMD_USER_LOGIN:
        {
            int ret;
            if ( cmd->cmdDataLength > 0 )
            {
                ret = *(int *)cmd->cmdData;
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [_ProgressHUD hide:YES];
                    
                });
                if(ret == 0)
                {
                    [self performSelectorOnMainThread:@selector(logText:) withObject:@"登录成功" waitUntilDone:NO];
                    
                    [GlobalInfo sharedInstance].remoteArray = [NSMutableArray array];
                    
                    [WISInterfaces wis_send_get_devices_cmd:[GlobalInfo sharedInstance].m_CmdSock];
                    

                    if(remoteDeviceTimer == nil && ![remoteDeviceTimer isValid])
                    {
                        remoteDeviceTimer = [NSTimer timerWithTimeInterval:2 target:self selector:@selector(getRemoteDeviceTimerMethod) userInfo:nil repeats:YES];
                        
                        [[NSRunLoop mainRunLoop] addTimer:remoteDeviceTimer forMode:NSDefaultRunLoopMode];
                    }
                    
                }
                else
                {
                    [self performSelectorOnMainThread:@selector(logText:) withObject:@"登录失败" waitUntilDone:NO];
                }
            }
            else
            {
                [self performSelectorOnMainThread:@selector(logText:) withObject:@"登录失败" waitUntilDone:NO];
            }
            
            break;
        }
            /* bind  */
        case WIS_CMD_USER_BIND:
        {
            int ret;
            if ( cmd->cmdDataLength > 0 )
                ret = *(int *)cmd->cmdData;
            break;
        }
            
            /* unbind */
        case WIS_CMD_USER_UNBIND:
        {
            int ret;
            if ( cmd->cmdDataLength > 0 )
                ret = *(int *)cmd->cmdData;
            break;
        }
            
            /* get devices list  */
        case WIS_CMD_USER_GET_DEVICES:
        {
            wis_user_dev_list *list = NULL;
            if ( cmd->cmdDataLength > 0 )
            {
                list = (wis_user_dev_list *)cmd->cmdData;
                
                dispatch_sync(dispatch_get_main_queue(), ^{
                    //[_upnpController remoteDeviceHasReached:list];
                
                    //add by anson 14-03
                    if ([self.navigationController.topViewController isMemberOfClass:[DemoUpnpViewController class]]) {
                        DemoUpnpViewController *vc = (DemoUpnpViewController *)self.navigationController.topViewController;
                        [vc remoteDeviceHasReached:list];
                    }else
                        [self remoteDeviceHasReached:list];
                    
                });
            }
            
            break;
        }
            
            /* get device  info*/
        case WIS_CMD_USER_GET_DEVICE_INFO:
        {
            wis_user_dev_info *dev = NULL;
            if ( cmd->cmdDataLength > 0 )
                dev = (wis_user_dev_info *)cmd->cmdData;
            
            
            break;
        }
        case WIS_CMD_USER_HEART_BEAT:
        {
            [WISInterfaces wis_send_heartbeat_cmd:[GlobalInfo sharedInstance].m_CmdSock];
            
            break;
        }
            
            //add by anson 14-03
        case WIS_CMD_USER_PRIVATE:
        {
            int ret = -1;
            if ( cmd->cmdDataLength > 0 )
                ret = *(int *)cmd->cmdData;
            DLog("WIS_CMD_USER_PRIVATE %s ret=%d\n", ret?"failed":"succeed", ret);
            break;
        }
            
        case WIS_CMD_RESULT:
        {
            DLog("===== %s receive cmd : WIS_CMD_RESULT ===== \n", __FUNCTION__);
            
            int len = cmd->cmdDataLength - sizeof(wis_result);
            wis_result * result = (wis_result *)cmd->cmdData;
            DLog("%s  uuid[%s] len[%d]\n", __FUNCTION__, result->session_id, len);
            int i;
            for(i=0; i<len; ++i)
                DLog("result[%d]=0x%.2x\n", i, result->data[i]);
            
            break;
        }
            
        case WIS_CMD_TO_USER:
        {
//            DLog("===== receive cmd : WIS_CMD_TO_USER ===== \n");
            if ( cmd->cmdData && cmd->cmdDataLength >= 32 )
            {
                int len = cmd->cmdDataLength - 32;
                DLog("from dev[%s] to_user dlen = %d\n", cmd->cmdData, len);
				UserCmdRet_t *cmdRet = (UserCmdRet_t*)(((wis_result*)cmd->cmdData)->data);
                if (!cmdRet) {
                    DLog(@" cmdRet is NULL ");
                    return;
                }
                
				if (cmdRet->cmd == 0x1000)
				{
					SysInfo_t *sys = (SysInfo_t*)cmdRet->data;
					DLog("[cmdid=0x%x,stat=%d,data_len=%d]:\n", cmdRet->cmd, cmdRet->stat, cmdRet->data_len);
					DLog("-->name=%s\n",sys->name);
					DLog("-->hw_ver=%s\n",sys->hw_ver);
					DLog("-->sw_ver=%s\n",sys->sw_ver);
					DLog("-->mac_addr=%s\n",sys->mac_addr);
					DLog("-->local_ip_addr=%s\n",sys->local_ip_addr);
					DLog("-->public_ip_addr=%s\n",sys->public_ip_addr);
					DLog("-->http_port=%s\n",sys->http_port);
					DLog("-----------------\n ");
				}else{
                    
                    NSDictionary *dic = [[NSDictionary alloc] init];
                    if (cmdRet->data_len == 0)
                    {
                        dic = @{@"cmdid": [NSNumber numberWithInt:cmdRet->cmd]};
                    }
                    else
                    {
        
                        char a[32];
                        memcpy(a,cmd->cmdData, 32);
                        NSData *cmddata = [NSData dataWithBytes:a length:32];
                        NSString *stringgg = [[NSString alloc] initWithData:cmddata encoding:NSUTF8StringEncoding];
                        
                        //判断更新的主机状态是否是当前的主机
                        if(cmdRet->cmd == 0x2006)
                        {
                            //有点逗的地方，不这样还不行
                            NSString *upString = [stringgg stringByReplacingOccurrencesOfString:@":" withString:@""];
                            const char * upChar =[upString UTF8String];
                            NSString *uppString=[NSString stringWithCString:upChar encoding:NSUTF8StringEncoding];
        
                            if([[GlobalService sharedInstance].curOperationDeviceUUID length] <= 0)
                            {
                                return;
                            }
                            NSString *dpString = [[GlobalService sharedInstance].curOperationDeviceUUID stringByReplacingOccurrencesOfString:@":" withString:@""];
                            const char * dpChar =[dpString UTF8String];
                            NSString *dppString=[NSString stringWithCString:dpChar encoding:NSUTF8StringEncoding];
                            
                            if ([uppString isEqualToString:dppString])
                            {
                                NSLog(@"stringgg:%@",upString);
                            }
                            else if(![upString isEqualToString:dpString])
                            {
                                NSLog(@"不是同一个设备");
                                return;
                            }
                        }
                        
                        NSData *data = [NSData dataWithBytes:cmdRet->data length:cmdRet->data_len];
                        
                        if( [data length] == 0)
                        {
                            NSLog(@"An error must have occurred");
                        } else {
                            NSLog(@"The data length: %lu", (unsigned long)[data length]);
                        }
                        
                        NSString *jsonStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                        
                        NSLog(@"jsonStr----------:%@",jsonStr);
                        
                        if (jsonStr.length == 0)
                        {
                            NSLog(@"123456789");
                        }
                        
                        DLog("[cmdid=0x%x, stat=%d, data_len=%d]:\n %@\n", cmdRet->cmd, cmdRet->stat, cmdRet->data_len, jsonStr);
                         dic = @{@"jsondata": data, @"cmdid": [NSNumber numberWithInt:cmdRet->cmd]};
                    }
                    [self performSelectorOnMainThread:@selector(sendServerResponseCMDData:) withObject:dic waitUntilDone:NO];
				}
				
//                 for(int i=0; i<cmd->cmdDataLength; ++i)
//                     NSLog(@"data[%d]=0x%.2x\n", i, cmd->cmdData[32+i], cmd->cmdData[32+i]);
            }
            break;
        }
        
        case WIS_CMD_CGI_URL:
        {
            DLog();
            break;
        }
        default:
        {
        	int i;
            DLog("===== %s unknown cmd : 0x%x len=%d ===== \n",
                 __FUNCTION__, cmd->cmdId, cmd->cmdDataLength);
       	 	for(i = 0; i < cmd->cmdDataLength; ++i)
            	DLog("data[%d]=0x%.2X=[%c]\n",
                     i, cmd->cmdData[i], cmd->cmdData[i]);
        }
            break;
            
    }
}

-(void)logText:(NSString *)log
{
    DLog(@"%@", log);
}

- (void)promptMsg:(NSString *)msg {
    
    [self.view makeToast:msg duration:1.0 position:@"center"];
}

- (void)sendServerResponseCMDData:(id)data {
    
    NSInteger cmdId = [[data objectForKey:@"cmdid"] integerValue];
    NSData *devJsonData = [data objectForKey:@"jsondata"];
    if (cmdId == WIS_CMD_V2_DEV_STAT_CHANGE_GET) {
        
        DLog(@"WIS_CMD_V2_DEV_STAT_CHANGE_GET");
        [[CMDDataProcessor sharedInstance] updateDevStatusChangeData:devJsonData];
        
    }else if (cmdId == WIS_CMD_V2_DEV_LIST_GET) {
        
//        if(_deviceStatusUpdateTimer == nil && ![_deviceStatusUpdateTimer isValid])
//        {
//            _deviceStatusUpdateTimer = [NSTimer timerWithTimeInterval:DEVICE_STATUS_UPDATE_TIMER_INTERVAL target:self selector:@selector(getDeviceStatusUpdateTimerMethod) userInfo:nil repeats:YES];
//            //[_deviceStatusUpdateTimer fire];
//            
//            [[NSRunLoop mainRunLoop] addTimer:_deviceStatusUpdateTimer forMode:NSDefaultRunLoopMode];
//            
//            
//        }
        
        [[CMDDataProcessor sharedInstance] revServerDevListData:devJsonData];
        
    }else
        [[CMDDataProcessor sharedInstance] revServerDataCall:devJsonData];

}

#pragma mark - 
//- (void)getDeviceStatusUpdateTimerMethod {
//
//    [WISInterfaces wis_send_private_cmd:[GlobalInfo sharedInstance].m_CmdSock cmdId:WIS_CMD_V2_DEV_STAT_CHANGE_GET data:(char *)[[[GlobalInfo sharedInstance] getUniqueID] UTF8String] len:32 uuid:(char *)[[GlobalService sharedInstance].curOperationDeviceUUID UTF8String]];
//    
//    
//}

-(void)remoteDeviceHasReached:(wis_user_dev_list *)remoteList
{
    int countArr[32]={0};
    BOOL needToRefreshUpnp = NO;
    
    for(int i = 0; i < remoteList->num; ++i)
    {
        wis_user_dev * remoteDev = &remoteList->devs[i];
        BOOL isExsit = NO;
        for(int j = 0; j < [[GlobalInfo sharedInstance].remoteArray count]; j++)
        {
            NSValue * value = [[GlobalInfo sharedInstance].remoteArray objectAtIndex:j];
            wis_user_dev device;
            [value getValue:&device];
            
            //存在 更新状态
            if(strcmp(remoteDev->uuid, device.uuid) == 0)
            {
                isExsit = YES;
                if(remoteDev->status != device.status)
                {
                    NSValue * value = [NSValue valueWithBytes:remoteDev objCType:@encode(wis_user_dev)];
                    [[GlobalInfo sharedInstance].remoteArray replaceObjectAtIndex:j withObject:value];
                    
                    if(remoteDev->status == 0)
                    {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"PopRemoteControl" object:[NSString stringWithFormat:@"%s",device.uuid]];
                    }
                }
                
                countArr[j]=1;
                
                break;
            }
        }
        
        //增加
        if(isExsit == NO)
        {
            NSValue * value = [NSValue valueWithBytes:remoteDev objCType:@encode(wis_user_dev)];
            [[GlobalInfo sharedInstance].remoteArray addObject:value];
            
            countArr[[[GlobalInfo sharedInstance].remoteArray count]-1]=1;
            
            needToRefreshUpnp = YES;
        }
    }
    
    //删除服务器少的
    NSMutableArray * deleteArr = [NSMutableArray array];
    for(int j = 0; j < [[GlobalInfo sharedInstance].remoteArray count]; j++)
    {
        if(countArr[j] == 0)//没匹配到，说明服务器列表少了
        {
            [deleteArr addObject:[[GlobalInfo sharedInstance].remoteArray objectAtIndex:j]];
            needToRefreshUpnp = YES;
        }
    }
    
    for(NSValue * value in deleteArr)
    {
        [[GlobalInfo sharedInstance].remoteArray removeObject:value];
    }
    
    NSValue *value = [[GlobalInfo sharedInstance].remoteArray lastObject];
    if (value && [GlobalService sharedInstance].curOperationDeviceUUID.length == 0) {
        
        wis_user_dev device;
        [value getValue:&device];
        
        NSString *devUUID = [NSString stringWithFormat:@"%s",device.uuid?device.uuid:""];
        [GlobalService sharedInstance].curOperationDeviceUUID = devUUID;
        //cell.contentLabel.text = [NSString stringWithFormat:@"%s",device.name?device.name:"NoName"];
        [self updateNavTitle:devUUID];
        
        //[cell setStatus:device.status withVersion:0];
    }    

}

#pragma mark -
- (void)updateNavTitle:(NSString *)title {
 
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(100, 0, 120, 44)];
    titleLabel.font = [UIFont boldSystemFontOfSize:16];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.backgroundColor = [UIColor clearColor];
    titleLabel.textAlignment = NSTextAlignmentCenter;
    titleLabel.text = title;
    self.navigationItem.titleView = titleLabel;
   
}


#pragma mark - Detect uPNP device
- (void)inituPnPDetect {
    // Do any additional setup after loading the view from its nib.
    [[WiimuUpnp sharedInstance] addDelegate:self];
    [[WiimuUpnp sharedInstance] beginSSDP:devWifiAudio];
    
    //DDFileLogger *fileLogger = [[DDFileLogger alloc] init];

    
    NSString *applicationDocumentsDirectory = [[[[NSFileManager defaultManager]
                                                  URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject] path];
    DDLogFileManagerDefault *documentsFileManager = [[DDLogFileManagerDefault alloc]
                                                     initWithLogsDirectory:applicationDocumentsDirectory];
    DDFileLogger *fileLogger = [[DDFileLogger alloc]
                                initWithLogFileManager:documentsFileManager];
    
    
    fileLogger.rollingFrequency = 60 * 60 * 24; // 24 hour rolling
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;
    [DDLog addLogger:fileLogger];
    
    DDLogVerbose(@"%s  Begin Logger ", __FUNCTION__);
    
}

#pragma mark - WiimuUpnp Delegate
//WiimuUpnp delegate callback
-(void)netWorkStatusChanged:(Reachability*) curReach
{
    NetworkStatus Status = [curReach currentReachabilityStatus];
    
    if(Status != ReachableViaWiFi)
    {
        [[WiimuUpnp sharedInstance] stopSSDP];
        
        DDLogVerbose(@"%s 请将手机连接到Wi-Fi网络", __FUNCTION__);
        [_deviceArr removeAllObjects];
        
        //[self.menuView reloadData];
    }
    else
    {
        [[WiimuUpnp sharedInstance] beginSSDP:devWifiAudio];
    }
    [self connectNieTechWISServer];
}

-(void)newDeviceCome:(NSDictionary *)device
{
    
    [_deviceArr addObject:device];
    
    DDLogVerbose(@"%s  %@ _deviceArrCount:%d", __FUNCTION__, device, _deviceArr.count);

}

-(void)deviceInfoChange:(NSDictionary *)device
{
    DDLogVerbose(@"%s  %@", __FUNCTION__, device);
    for(int i=0; i<[_deviceArr count]; i++)
    {
        NSDictionary * dic = [_deviceArr objectAtIndex:i];
    
        //mod by anson
        if([dic[@"baseURL"] isEqualToString:device[@"baseURL"]])
        {
            [_deviceArr replaceObjectAtIndex:i withObject:device];
            break;
        }
    }
    
    //[self.menuView reloadData];
}

-(void)deviceDisappear:(NSDictionary *)device
{
    DDLogVerbose(@"%s  %@", __FUNCTION__, device);
    
    int i;
    for(i=0; i<[_deviceArr count]; i++)
    {
        NSDictionary * dic = [_deviceArr objectAtIndex:i];
        
        if([dic[@"baseURL"] isEqualToString:device[@"baseURL"]])
        {
            break;
        }
    }
    
    if (i<[_deviceArr count]) {
        [_deviceArr removeObjectAtIndex:i];
    }
    
    //[self.menuView reloadData];
}

-(void)allDevicesDisappear
{
    DDLogVerbose(@"%s", __FUNCTION__);
    [_deviceArr removeAllObjects];
//    [self.menuView reloadData];
}
#pragma mark - UIActionSheetDelegate 、UIAlertViewDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == 200) {
        
        if (buttonIndex == 0)
        {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请按住设备上的按钮" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
            alertView.tag = 200;
            [alertView show];
        }
        else if (buttonIndex == 1)
        {
            if (ipUrl)
            {
                [MMProgressHUD showWithTitle:@"提示"
                                      status:@"请点击设备上的按钮"
                         confirmationMessage:@"确定取消删除设备？"
                                 cancelBlock:^{
                                 }];
                [self deleteOneDevice];
            }
            else
            {
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"只有在局域网情况下才能删除或者添加设备" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
                [alert show];
            }
        }
        return;
    }
    
    //NSLog(@"index:%d",buttonIndex);
    if (buttonIndex == 0)
    {
        UIAlertView *resetAlertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"确定RESET DEVICE？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        resetAlertView.tag = 100;
        [resetAlertView show];
    }
    else if(buttonIndex == 1)
    {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请按住设备上的按钮" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定",nil];
        alertView.tag = 200;
        [alertView show];
    }
    else if(buttonIndex == 2)
    {
        [MMProgressHUD showWithTitle:@"提示"
                              status:@"请点击设备上的按钮"
                 confirmationMessage:@"确定取消删除设备？"
                         cancelBlock:^{
                         }];
        [self deleteOneDevice];
    }
}

#pragma mark - UIAlerView Delegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSLog(@"index:%ld",buttonIndex);
    if (alertView.tag == 100) {
        if (buttonIndex == 1)
        {
            [MMProgressHUD showWithTitle:@"RESETTING......"];
            [self resetZWaveDevice];
        }
    }else if(alertView.tag == 200)
    {
        if (buttonIndex == 1)
        {
            [self addOneDevice];
        }
    }
}

#pragma mark ---
//reset device
- (void)resetZWaveDevice
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
        NSString *resetStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=5",ipUrl];
        [Utitlity commonHTTPMethod:resetStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSLog(@"respon:%@",responseObject);
            
            if ([responseObject[@"state"] isEqualToString:@"Success"])
            {
                [MMProgressHUD dismissWithSuccess:@"RESET成功"];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}
//add a device
- (void)deleteOneDeviceIn
{
    ipUrl = [Utitlity judgeipUrl];
    
    [MMProgressHUD showWithTitle:@"提示"
                          status:@"添加设备中。。。。"
             confirmationMessage:@"确定取消添加设备？"
                     cancelBlock:^{
                         [self cancleNode];
                     }];
    
    if (ipUrl)
    {
        NSString *deleStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=2",ipUrl];
        [Utitlity commonHTTPMethod:deleStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (!responseObject || ![responseObject isKindOfClass:[NSData class]]) return;
            NSString * responseStr = [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
            NSDictionary *item = [responseStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
            NSArray *tempArr = [item objectForKey:@"data"];
            NSDictionary *dic = [tempArr firstObject];
            NSString *zid = dic[@"ZID"];
            
            PersistableInfo *info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where zid='%@'",zid];
            if(info)
            {
                [info delete:zid];
            }
            
            NSString *status = item[@"state"];
            if ([status isEqualToString:@"Success"])
            {
                [self addOneDevice];
            }
            else
            {
                [MMProgressHUD dismissWithError:@"添加设备失败"];
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

- (void)addOneDevice
{
    ipUrl = [Utitlity judgeipUrl];
    
    if(ipUrl)
    {
        NSString *deviceStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=1",ipUrl];
        [Utitlity commonHTTPMethod:deviceStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            NSString * responseStr = [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
            
            NSArray *arr = [responseStr componentsSeparatedByString:@"\n"];
            NSString *reponse = [arr lastObject];
            NSDictionary *item = [reponse objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
            NSString *status = item[@"state"];
            if ([status isEqualToString:@"Success"])
            {
                [MMProgressHUD dismissWithSuccess:@"添加成功"];
            }
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"123error:%@",error);
            [MMProgressHUD updateTitle:@"添加失败" status:nil];
        }];
    }
}


//delete a device
- (void)deleteOneDevice
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl)
    {
       
        NSString *deleStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=2",ipUrl];
        [Utitlity commonHTTPMethod:deleStr responseType:stringType success:^(AFHTTPRequestOperation *operation, id responseObject)
         {
            if (!responseObject || ![responseObject isKindOfClass:[NSData class]]) return;
            
            NSString * responseStr = [[NSString alloc] initWithBytes:[responseObject bytes] length:[responseObject length] encoding:NSUTF8StringEncoding];
            NSDictionary *item = [responseStr objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
            NSArray *tempArr = [item objectForKey:@"data"];
            NSDictionary *dic = [tempArr firstObject];
            NSString *zid = dic[@"ZID"];
            
            PersistableInfo *info = (PersistableInfo *)[PersistableInfo findFirstByCriteria:@"where zid='%@'",zid];
            if(info)
            {
                [info delete:zid];
            }
            
            NSString *status = item[@"state"];
            if ([status isEqualToString:@"Success"])
            {
                [MMProgressHUD dismissWithSuccess:@"删除成功"];
            }
            else
            {
                [MMProgressHUD dismissWithError:@"删除失败"];
            }
//            else
//            {
//                [self deleteOneDevice];
//            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

//cancleNode
- (void)cancleNode
{
    NSString *deviceStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Mode.cgi?Mode=4",ipUrl];
    [Utitlity commonHTTPMethod:deviceStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if ([[responseObject[@"state"] lowercaseString] isEqualToString:@"success"])
        {
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

@end
